package top.lionkliu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

// 拦截所有的请求 解决全站中文乱码
@WebFilter("/*")
public class CharacterFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        // 指定 request 和 response 的编码
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");
        // 只对消息体有效
        res.setContentType("text/html;charset=utf-8");
        chain.doFilter(new CharacterRequest(req), res);
    }
}

class CharacterRequest extends HttpServletRequestWrapper{
    private HttpServletRequest request;


    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request the {@link HttpServletRequest} to be wrapped.
     * @throws IllegalArgumentException if the request is null
     */
    public CharacterRequest(HttpServletRequest request) {
        super(request);
        this.request=request;
    }

    public String getParameter(String name){
        String value =super.getParameter(name);
        if (value == null){
            return null;
        }
        String method = super.getMethod();
        if ("get".equalsIgnoreCase(method)){
            try {
                value = new String(value.getBytes("iso-8859-1"),"utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return value;
    }
}